//
//  KomplektViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/27/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation


final class KomplektViewModel {
    
    struct Komplekts {
        var result: [KomplektSection]
    }
    
    struct KomplektSection {
        var title: String = ""
        var items: [String] = []
        var isExpanded: Bool = true
        
        init (_ data: NSArray) {
            title = data[0] as? String ?? ""
            items = (data[1] as? [[String:String]] ?? []).map {
                $0.values[$0.values.startIndex]
            }
        }
    }
    
    public var data: [KomplektSection] = []
    
    private let backend = Backend()
    
    
    func loadData (carID: Int, completion: @escaping (Result <Bool, RequestError>) -> Void) {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "cars/custom-options/\(carID)/"))
        let headers = [ "content-type": "application/json", "authorization": User.shared.token ]
        request.allHTTPHeaderFields = headers
        
        let dataTask = URLSession.shared.dataTask(with: request) { (data, _, _) in
            DispatchQueue.main.async {
                guard let jsonData = data else {
                    return completion(.failure(.general))
                }
                
                var output: [KomplektSection] = []
                
                if let jsonData = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
                    if let results = (jsonData as! NSDictionary)["result"] as? NSArray {
                        for item in results {
                            output.append(KomplektSection(item as? NSArray ?? NSArray()))
                        }
                        self.data = output
                        completion(.success(true))
                    } else {
                        completion(.failure(.general))
                    }
                } else {
                    completion(.failure(.general))
                }
            }
        }
        
        dataTask.resume()
    }
}
